package cn.tjad.tjad2.module.design.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.bean.CommonListBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.CommonEntity;
import cn.tjad.tjad2.data.bean.DesignItem;
import cn.tjad.tjad2.data.bean.Type;
import cn.tjad.tjad2.data.event.DesignRefreshEvent;
import cn.tjad.tjad2.listener.OnItemClickListener;
import cn.tjad.tjad2.module.design.adapter.DesignListAdapter;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.AppUtils;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.widget.SingleChoicePopupWindow;

public class DesignFragment extends BaseFragment implements OnItemClickListener, OnRefreshLoadMoreListener, SingleChoicePopupWindow.OnItemClickListener {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.divider_line)
    View dividerLine;

    private DesignListAdapter designListAdapter;
    private List<DesignItem> designList = new ArrayList();

    private SingleChoicePopupWindow statusFilterWindow;
    private SingleChoicePopupWindow fieldFilterWindow;
    private SingleChoicePopupWindow typeFilterWindow;

    private int startIndex = 0;
    private final int PAGE_ACCOUNT = 10;
    //是否拼接数据
    private boolean appendData;

    private String status = ""; //0：草稿，1：进行中，2：已完成
    private String type = "";
    private String domain = "";
    private String userId;
    // 0 : 与我相关
    // 1 : 所有
    private int tabType = 0;

    private List<Type> designTypeList;

    public static DesignFragment newInstance(int tabType) {
        Bundle bundle = new Bundle();
        bundle.putInt("tabType", tabType);
        DesignFragment fragment = new DesignFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        Bundle args = getArguments();
        if (args != null) {
            tabType = args.getInt("tabType", 0);
        }
        if (tabType == 0) {
            userId = String.valueOf(TjadApplication.getInstance().getSession().getLoginInfo().id);
        }
    }

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.design_list_layout, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        designListAdapter = new DesignListAdapter(designList);
        designListAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(designListAdapter);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        if (tabType == 0) {
            refreshLayout.autoRefresh();
        }
        requestTypeIfNeeded();
    }

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (refreshLayout != null && designList.isEmpty()) {
                refreshLayout.autoRefresh();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        requestTypeIfNeeded();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void requestData() {
        Log.d("yanghongbing", "请求条目 " + tabType);
        RetrofitManager.getInstance().getApiService().
                getDesignList(Tools.getProjectId(), startIndex, PAGE_ACCOUNT, status, type, domain, userId)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<ArrayList<DesignItem>>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<ArrayList<DesignItem>> t) {
                        if (t.resCode == 0) {
                            CommonListBean listBean = (CommonListBean) t;
                            if (!appendData) {
                                designList.clear();
                            }
                            designList.addAll(t.result);
                            designListAdapter.notifyDataSetChanged();
                            if (listBean.pagination != null) {
                                startIndex = startIndex + listBean.pagination.limit;
                                if (designListAdapter.getItemCount() >= listBean.pagination.totalItems) {
                                    refreshLayout.finishLoadMoreWithNoMoreData();
                                }
                                DesignTabFragment parentFragment = (DesignTabFragment) getParentFragment();
                                if (parentFragment != null) {
                                    boolean isTotal = status == "" && type == "" && domain == "";
                                    parentFragment.updateCount(tabType, listBean.pagination.totalItems, isTotal);
                                }
                            }
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                        } else {
                            Tools.showToast(t.respMsg);
                        }
                    }

                    @Override
                    public void onFailed(String message) {
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                        Tools.showToast(message);
                    }
                });
    }

    private void sendRefreshEvent() {
        DesignRefreshEvent event = new DesignRefreshEvent(tabType);
        EventBus.getDefault().post(event);
    }

    @Subscribe
    public void onTabRefresh(DesignRefreshEvent event) {
        //不处理自己发的消息
        if (event.getFromType() == tabType) {
            return;
        }
        refreshCount();
    }

    private void refreshCount() {
        Log.d("yanghongbing", "刷新数目" + tabType);
        RetrofitManager.getInstance().getApiService().
                getDesignList(Tools.getProjectId(), 0, 1, status, type, domain, userId)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<ArrayList<DesignItem>>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<ArrayList<DesignItem>> t) {
                        if (t.resCode == 0) {
                            CommonListBean listBean = (CommonListBean) t;
                            if (listBean.pagination != null) {
                                DesignTabFragment parentFragment = (DesignTabFragment) getParentFragment();
                                if (parentFragment != null) {
                                    boolean isTotal = status == "" && type == "" && domain == "";
                                    parentFragment.updateCount(tabType, listBean.pagination.totalItems, isTotal);
                                }
                            }
                        } else {
                        }
                    }

                    @Override
                    public void onFailed(String message) {
                        Log.d("DesignFragment", message);
                    }
                });
    }

    private void requestTypeIfNeeded() {
        if (designTypeList != null) {
            return;
        }
        RetrofitManager.getInstance().getApiService()
                .getDesignType(Tools.getProjectId())
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<ArrayList<Type>>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<ArrayList<Type>> t) {
                        designTypeList = t.result;
                        Type all = new Type();
                        all.id = -1;
                        all.name = "全部";
                        designTypeList.add(0, all);
                    }

                    @Override
                    public void onFailed(String message) {
                        Log.d("designFragment", message);
                    }
                });
    }

    @Override
    public void onItemClick(View parentView, View itemView, int position) {
        Object data = designListAdapter.getItemData(position);
        if (data instanceof DesignItem) {
            Bundle bundle = new Bundle();
            bundle.putInt(Keys.DESIGN_ID, ((DesignItem) data).id);
            RouteUtils.toPage(getContext(), PageId.DESIGN_DETAIL, bundle);
        }
    }

    @OnClick({R.id.design_status, R.id.design_type, R.id.design_field})
    public void onFilterClick(View view) {
        switch (view.getId()) {
            case R.id.design_status:
                if (statusFilterWindow == null) {
                    String[] statusList = AppUtils.getStringArray(R.array.design_filter_status);
                    List<CommonEntity> entityList = new ArrayList<>();
                    for (int i =0; i < statusList.length; i++) {
                        CommonEntity entity = new CommonEntity();
                        entity.id = i;
                        entity.name = statusList[i];
                        entityList.add(entity);
                    }
                    statusFilterWindow = new SingleChoicePopupWindow(getContext(), entityList);
                    statusFilterWindow.setOnItemClickListener(this);
                }
                statusFilterWindow.showAsDropDown(dividerLine);
                break;
            case R.id.design_type:
                requestTypeIfNeeded();
                if (typeFilterWindow == null) {
                    typeFilterWindow = new SingleChoicePopupWindow(getContext(), designTypeList);
                    typeFilterWindow.setOnItemClickListener(this);
                }
                typeFilterWindow.showAsDropDown(dividerLine);
                break;
            case R.id.design_field:
                if (fieldFilterWindow == null) {
                    List<CommonEntity> entityList = new ArrayList<>();
                    String[] fieldList = AppUtils.getStringArray(R.array.design_filter_domain);
                    for (int i =0; i < fieldList.length; i++) {
                        CommonEntity entity = new CommonEntity();
                        entity.id = i;
                        entity.name = fieldList[i];
                        entityList.add(entity);
                    }
                    fieldFilterWindow = new SingleChoicePopupWindow(getContext(), entityList);
                    fieldFilterWindow.setOnItemClickListener(this);
                }
                fieldFilterWindow.showAsDropDown(dividerLine);
                break;
        }
    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        appendData = true;
        requestData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        appendData = false;
        startIndex = 0;
        requestData();
        sendRefreshEvent();
    }

    @Override
    public void onItemClick(SingleChoicePopupWindow window, CommonEntity entity) {
        if (window == statusFilterWindow) {
            if (entity.id == 0) {
                status = "";
            } else {
                status = String.valueOf(entity.id - 1);
            }
        } else if (window == typeFilterWindow) {
            if (entity.id == -1) {
                type = "";
            } else {
                type = String.valueOf(entity.id);
            }
        } else if (window == fieldFilterWindow) {
            if (entity.id == 0) {
                domain = "";
            } else {
                domain = entity.name;
            }
        }
        onRefresh(refreshLayout);
    }
}
